<template>
  <div class="main">
    <div class="goodMain">
      <!-- 面包屑 -->
      <app-link :name="title"></app-link>

      <!-- 搜索表单 -->
      <el-form :inline="true" :model="seachForm" class="demo-form-inline">
        <el-form-item>
          <el-input v-model="seachForm.name" placeholder="商品名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-select v-model="seachForm.type" placeholder="商品类别">
            <el-option label="新鲜水果" value="新鲜水果"></el-option>
            <el-option label="方便速食" value="方便速食"></el-option>
            <el-option label="海鲜水产" value="海鲜水产"></el-option>
            <el-option label="粮油杂货" value="粮油杂货"></el-option>
            <el-option label="精选肉类" value="精选肉类"></el-option>
            <el-option label="食品饮料" value="食品饮料"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="success" icon="el-icon-search" @click="fetchall">查询</el-button>
          <el-button type="success" icon="el-icon-refresh-left" @click="reset">重置</el-button>
          <el-button type="success" icon="el-icon-circle-plus-outline" @click="addGood">新增</el-button>
        </el-form-item>
      </el-form>

      <!-- 商品列表 -->
      <el-table :data="goodList" border style="width: 100%" stripe>
        <el-table-column type="index" label="序号" width="80"></el-table-column>
        <el-table-column prop="name" label="商品名称" width="250"></el-table-column>
        <el-table-column prop="message" label="商品简介" width="240"></el-table-column>
        <el-table-column prop="type" label="商品类别" width="100"></el-table-column>
        <el-table-column label="商品图片" width="150">
          <template slot-scope="scope">
            <!-- scope指整个数据对象，scope.row指当前行数据 -->
            <img :src="scope.row.src[0]" alt style="width:70px;height: 60px;" />
          </template>
        </el-table-column>
        <el-table-column prop="size" label="商品规格" width="100"></el-table-column>
        <el-table-column prop="price" label="商品价格" width="100"></el-table-column>
        <el-table-column label="操作" width="220">
          <template slot-scope="scope">
            <el-button type="success" icon="el-icon-edit" @click="editGood(scope.row)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" @click="delGood(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 新增 商品-->
      <el-dialog :title="isAdd ? '新增商品' : '修改商品 '" :visible.sync="dialogFormVisible">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm">
          <el-form-item label="商品名称" prop="name" :label-width="formLabelWidth">
            <el-input v-model="ruleForm.name" placeholder="请输入商品名称" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="商品简介" prop="message" :label-width="formLabelWidth">
            <el-input v-model="ruleForm.message" placeholder="请输入商品简介" autocomplete="off"></el-input>
          </el-form-item>

          <el-form-item label="商品类别" prop="type" :label-width="formLabelWidth">
            <el-select v-model="ruleForm.type" placeholder="请选择商品类别">
              <el-option label="新鲜水果" value="新鲜水果"></el-option>
              <el-option label="方便速食" value="方便速食"></el-option>
              <el-option label="海鲜水产" value="海鲜水产"></el-option>
              <el-option label="粮油杂货" value="粮油杂货"></el-option>
              <el-option label="精选肉类" value="精选肉类"></el-option>
              <el-option label="食品饮料" value="食品饮料"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="商品照片" prop="src" :label-width="formLabelWidth">
            <el-upload
              class="upload-demo"
              ref="upload"
              action="/dev-api/good/add"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-change="onChange"
              :before-remove="beforeRemove"
              multiple
              :limit="1"
              :on-exceed="handleExceed"
              :file-list="fileList"
              name
              :auto-upload="false"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-form-item>
          <el-form-item label="商品规格" prop="size" :label-width="formLabelWidth">
            <el-input v-model="ruleForm.size" placeholder="请输入商品规格" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="商品价格" prop="price" :label-width="formLabelWidth">
            <el-input v-model.trim="ruleForm.price" placeholder="请输入商品价格" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="isAdd ? add() : edit()">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 分页 -->
      <el-pagination
        v-show="pages > 1"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
  </div>
</template>

<script>
import appLink from "@/components/link";
// 引入接口文档
import goodApi from "@/api/goodApi.js";
export default {
  data() {
    var validatePrie = (rule, value, callback) => {
      /*
        value:表单的value
        callback:回调函数，返回提示信息
      */
      let reg = /^\d{0,5}\.?\d{0,2}$/;
      if (reg.test(value)) {
        callback();
      } else {
        callback(new Error("请输入正确的价格格式"));
      }
    };

    return {
      title: "商品管理",
      seachForm: {}, //查询条件
      page: 1, //页码
      pagesize: 10, //一页多少条数据
      total: 0, //总数据条数
      pages: 2, //分几页
      dialogFormVisible: false, //新增开关
      ruleForm: {
        name: "",
        message: "",
        type: "",
        size: "",
        price: ""
      },
      fileList: [], //上传文件
      rules: {
        name: [
          { required: true, message: "商品名称不能为空", trigger: "blur" } //商品名称不能为空
          // { validator: validateName, trigger: "blur" } //验证商品名称是否为空
        ],
        type: [
          { required: true, message: "商品类别不能为空", trigger: "blur" }
          // { validator: validateName, trigger: "blur" }
        ],
        size: [
          { required: true, message: "商品规格不能为空", trigger: "blur" }
          // { validator: validateName, trigger: "blur" }
        ],
        price: [
          { required: true, message: "商品价格不能为空", trigger: "blur" },
          { validator: validatePrie, trigger: "blur" }
        ]
      }, //表单正则规则
      formLabelWidth: "120px",
      goodList: [
        //商品列表
        // {
        //   good_id: 1,
        //   name: "Zespri佳沛新西兰阳光绿奇异果6个105-124g/个",
        //   message: "佳沛品牌 一口酸甜 清香爽口",
        //   price: "33.90",
        //   size: "6个/盒",
        //   type: "新鲜水果",
        //   src:
        //     "[http://img09.yiguoimg.com/d/items/2019/190601/9288738152457921_500.jpg,http://img14.yiguoimg.com/d/items/2019/190601/9288738152425153_500.jpg,http://img14.yiguoimg.com/d/items/2019/190530/9288738139121342_500.jpg,http://img10.yiguoimg.com/d/items/2019/190530/9288738139186878_500.jpg]",
        //   xqimg:
        //     "[http://img11.yiguoimg.com/d/images/2019/190530/513691896404780734_880x415.jpg,http://img12.yiguoimg.com/d/images/2019/190530/513691896405042878_880x1251.jpg,http://img09.yiguoimg.com/d/images/2019/190530/513691896404747966_880x1251.jpg,http://img13.yiguoimg.com/d/images/2019/190530/513691896404813502_880x1439.jpg,http://img11.yiguoimg.com/d/images/2019/190530/513691896404846270_880x1156.jpg,http://img11.yiguoimg.com/d/images/2019/190530/513691896405010110_880x1396.jpg,http://img13.yiguoimg.com/d/images/2019/190530/513691896404879038_880x1850.jpg,http://img13.yiguoimg.com/d/images/2019/190530/513691896404911806_880x939.jpg,http://img12.yiguoimg.com/d/images/2019/190530/513691896404944574_880x1114.jpg,http://img10.yiguoimg.com/d/images/2019/190530/513691896404977342_880x924.jpg,http://img13.yiguoimg.com/d/images/2017/171027/513691872596960091_1125x414.jpg]"
        // },
      ], //商品列表
      isAdd: true //对话框类别初始框 ture：添加用户
    };
  },

  components: { appLink },

  methods: {
    // 进入页面渲染数据、模糊查询
    async fetchall() {
      try {
        let p = await goodApi.getList(this.page, this.pagesize, this.seachForm);
        console.log(p.data);
        if (p.data.data.length) {
          this.goodList = p.data.data; //数据列表
          this.goodList.forEach(item => {
            item.src = item.src.replace("[", "");
            item.src = item.src.replace("]", "");
            item.src = item.src.split(",");
          });
          // console.log(this.goodList);
          this.total = p.data.totla; //总数据条数
          if (p.data.typetotla) {
            this.total = p.data.typetotla;
            this.pages = p.data.typepages;
          }
        } else {
          this.$message({
            message: "找不到数据，换个条件试试",
            type: "warnning"
          });
        }
      } catch (err) {
        this.$message({
          message: "找不到数据，换个条件试试",
          type: "warnning"
        });
      }
    },

    // 功能：重置
    reset() {
      this.seachForm = {};
      this.page = 1; //页码
      this.thispagesize = 10; //一页多少条数据
      this.total = 0; //总数据条数
      this.pages = 2;
      this.fetchall();
    },

    // 功能：打开添加商品弹窗
    addGood() {
      this.isAdd = true; //添加用户，开关设置为true
      this.dialogFormVisible = true; //打开新增表单
      // this.ruleForm = {}; //每次打开弹出清空表单
      this.fileList = []; //清空图片列表
      this.$nextTick(() => {
        //清空表单验证
        // this.$nextTick()它是一个异步事件，当渲染结束 之后 ，它的回调函数才会被执行
        // 弹出窗口打开之后 ，需要加载Dom, 就需要花费一点时间，我们就应该等待它加载完dom之后，再进行调用resetFields方法，重置表单和清除样式
        this.$refs["ruleForm"].resetFields();
        this.ruleForm = {}; //每次打开弹出清空表单
      });
    },

    // 功能：确定添加
    add() {
      this.$refs.ruleForm.validate(async res => {
        console.log(res, "#####");
        if (res) {
          // 手动提交图片，允许上传
          this.$refs.upload.submit(); //提交图片
          // 正则通过，运行上传数据添加新用户
          let form = new FormData();
          form.append("name", this.ruleForm.name);
          form.append("message", this.ruleForm.message);
          form.append("type", this.ruleForm.type);
          form.append("size", this.ruleForm.size);
          form.append("price", this.ruleForm.price);

          console.log(this.fileList, "filenameeeeeeeeeee");
          this.fileList.forEach(file => {
            form.append("avatar", file.raw);
            form.append("fileNames", file.name);
          });

          try {
            let p = await goodApi.addGoods(form);
            // console.log(p.data);
            if (p.data.flag) {
              // 提交成功
              this.$message({
                message: "添加成功",
                type: "success"
              });
              this.dialogFormVisible = false;
            } else {
              this.$message({
                message: "添加失败",
                type: "error"
              });
            }
          } catch (err) {
            console.log(err);
          }
        } else {
          // 正则不通过，不允许上传
          this.$message({
            message: "注意书写条件",
            type: "error"
          });
        }
      });
    },

    // 功能：打开修改商品弹窗
    editGood(row) {
      console.log(row.good_id, 999);
      this.isAdd = false; //编辑弹窗设置为false
      this.dialogFormVisible = true; //打开弹窗
      this.fileList = [];
      this.ruleForm = row;
      // console.log("ruleForm", this.ruleForm.src[0].split("/")[7]);
      // console.log("ruleForm", this.ruleForm.src);
      let obj = {
        name: "",
        url: this.ruleForm.src[0]
      };
      if (this.ruleForm.fileNames) {
        obj.name = this.ruleForm.fileNames;
      } else {
        obj.name = this.ruleForm.src[0].split("/")[7];
      }
      this.fileList.push(obj);
      console.log("obj", obj);
    },

    // 功能：确定修改
    edit() {
      console.log("修改数据");
      this.$refs.upload.submit(); //提交图片
      // 正则通过，运行上传数据添加新用户
      let form = new FormData();
      form.append("name", this.ruleForm.name);
      form.append("message", this.ruleForm.message);
      form.append("type", this.ruleForm.type);
      form.append("size", this.ruleForm.size);
      form.append("price", this.ruleForm.price);

      console.log(this.fileList, "filenameeeeeeeeeee");

      // this.fileList.forEach(file => {
      console.log(this.fileList[0].url);
      // 接口那边：req.files
      if (this.fileList[0].raw) {
        form.append("avatar", this.fileList[0].raw);
        form.append("fileNames", this.fileList[0].name);
      }

      // form.append("fileNames", this.fileList[0].name);
      // });
      // 把数据以form-data的格式发送过去
      console.log(this.ruleForm, "最后！！！！");

      goodApi.editgood(this.ruleForm.good_id, form).then(res => {
        if (res.data.flag) {
          //  修改成功
          this.$message({
            message: "修改成功",
            type: "success"
          });
          // 关闭弹窗，并刷新数据
          this.dialogFormVisible = false;
          this.fetchall();
        } else {
          this.$message({
            message: "修改失败",
            type: "error"
          });
        }
      });
    },

    // 功能：删除商品
    delGood(row) {
      console.log(row.good_id, "#####");
      this.$confirm("此操作将永久删除该商品, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          //确定
          let p = await goodApi.delgood(row.good_id);
          console.log(p.data);
          if (p.data.flag) {
            //  删除成功
            this.$message({
              message: "删除成功",
              type: "success"
            });
            // 关闭弹窗，并刷新数据
            this.dialogFormVisible = false;
            this.fetchall();
          } else {
            this.$message({
              message: "失败",
              type: "error"
            });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },

    // 功能：分页 每页条数
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pagesize = val; //每页多少条
      this.page = 1;
      this.fetchall();
    },
    // 功能：分页 当前页面
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.page = val;
      this.fetchall();
    },
    // 功能：删除已上传图片
    async handleRemove(file, fileList) {
      console.log(file, fileList);
      console.log(this.ruleForm.good_id);
      let p = await goodApi.delgoodphoto(this.ruleForm.good_id);
      console.log(p.data);
      if (p.data.flag) {
        this.$message({
          message: "删除成功",
          type: "success"
        });
      } else {
        this.$message({
          message: "删除失败",
          type: "error"
        });
      }
    },
    // 查看上传文件
    onChange(file, fileList) {
      this.fileList = fileList;
      console.log(fileList);
    },

    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      );
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    }
  },
  created() {
    // 进入页面就发请求
    this.fetchall();
  }
};
</script>

<style scoped>
.el-form {
  margin-top: 20px;
}
</style>
<style >
.goodMain .el-pagination .el-pager li:hover {
  border: 1px solid #67c23a;
}
.goodMain .el-pagination .el-pager .active {
  background: #67c23a;
  color: #fff;
  cursor: pointer;
}
.goodMain .el-pager li:hover {
  color: #67c23a;
}
.goodMain .line {
  border-left: 5px solid #67c23a;
}
.el-table .cell {
  text-align: center;
}
</style>